package com.css.zfzx.sjcj.modules.repository.impl;

import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.org.dept.repository.entity.DeptEntity;
import com.css.bpm.platform.org.division.repository.DivisionRepository;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.bpm.platform.org.role.repository.entity.RoleEntity;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.zfzx.sjcj.common.division.service.MyDivisionService;
import com.css.zfzx.sjcj.common.utils.ServerUtil;
import com.css.zfzx.sjcj.common.vo.DivisionVo;
import com.css.zfzx.sjcj.modules.pojo.PcProgressFillEntity;
import com.css.zfzx.sjcj.modules.repository.PcProgressFillNativeRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.Iterator;
import java.util.List;

/**
 * @Description: pc-statistics
 * @Author: lhl
 * @CreateDate: 2021/7/6 16:26
 */
@Repository
public class PcProgressFillNativeRepositoryImpl<T> implements PcProgressFillNativeRepository<T> {
    @PersistenceContext
    private EntityManager em;
    private static final Logger log = LoggerFactory.getLogger(PcProgressFillNativeRepositoryImpl.class);
    @Value("${spring.jpa.properties.hibernate.jdbc.batch_size}")
    private int BATCH_SIZE;

    @Override
    @Transactional
    public <S extends T> Iterable<S> batchUpdate(Iterable<S> var1) {
        Iterator<S> iterator = var1.iterator();
        int index = 0;
        while (iterator.hasNext()) {
            em.merge(iterator.next());
            index++;
            if (index % BATCH_SIZE == 0) {
                em.flush();
                em.clear();
            }
        }
        if (index % BATCH_SIZE != 0) {
            em.flush();
            em.clear();
        }
        return var1;
    }

    @Override
    @Transactional
    public <S extends T> Iterable<S> batchSave(Iterable<S> var1) {
        Iterator<S> iterator = var1.iterator();
        int index = 0;
        while (iterator.hasNext()) {
            em.persist(iterator.next());
            index++;
            if (index % BATCH_SIZE == 0) {
                em.flush();
                em.clear();
            }
        }
        if (index % BATCH_SIZE != 0) {
            em.flush();
            em.clear();
        }
        return var1;
    }

    @Override
    public List<PcProgressFillEntity> findByTaskCode(String taskCode, String userId) {
        StringBuilder sql = new StringBuilder("select * from pc_progress_fill ");
        StringBuilder whereSql = new StringBuilder(" where 1=1 ");
        //whereSql.append(" and is_valid = 1");
        if (!StringUtils.isEmpty(taskCode)) {
            whereSql.append(" and parent_code = :parentCode");
        }else {
            whereSql.append(" and level = 1");
        }
        //筛选项 筛选人员权限 省对应省 县对应县
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
        String divisionName = mainDept.getDeptName();
        //是否为终极质检员
        boolean containtRole = ServerUtil.isContaintRole(roles, superAdmin);
        //只控制是否是省级管理圆
        if (!containtRole) {
            //省级  返回对应的省级数据
            whereSql.append(" and division_name = :divisionName");
        }
        Query query = this.em.createNativeQuery(sql.append(whereSql).toString(), PcProgressFillEntity.class);
        if (!containtRole) {
            query.setParameter("divisionName", divisionName);
        }
        if (!StringUtils.isEmpty(taskCode)) {
            query.setParameter("parentCode", taskCode);
        }
        List<PcProgressFillEntity> list = query.getResultList();
        return list;
    }

    @Autowired
    private DivisionRepository divisionRepository;
    //超级管理员
    static String superAdmin = "pcjd";

    @Override
    public Object queryPcProgressDataSq(String taskCode, String menuId, String divisionCode) {
        StringBuilder sql = new StringBuilder("select * from pc_progress_fill");
        StringBuilder whereSql = new StringBuilder();
        whereSql.append(" where division_code = :divisionCode and task_code = :taskCode");
        Query query = this.em.createNativeQuery(sql.append(whereSql).toString());
        query.setParameter("divisionCode", divisionCode);
        query.setParameter("taskCode", menuId);
        Object result = null;
        try {
            result = query.getSingleResult();
        } catch (NoResultException e) {

        }
        return result;
    }
}
